{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e616fd0a-1ecf-47dd-bdbd-67c5c3c998d9",
   "metadata": {},
   "source": [
    "https://blog.langchain.dev/reflection-agents/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d4cbb222-b4f8-4dd1-8a5c-0426939fbc13",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-22T14:01:35.170695Z",
     "iopub.status.busy": "2024-11-22T14:01:35.170422Z",
     "iopub.status.idle": "2024-11-22T14:01:35.176674Z",
     "shell.execute_reply": "2024-11-22T14:01:35.175472Z",
     "shell.execute_reply.started": "2024-11-22T14:01:35.170673Z"
    }
   },
   "outputs": [],
   "source": [
    "from IPython.display import Image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3c5069d3-0e5e-44c6-a96f-9cc54b50099b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-22T14:01:36.353329Z",
     "iopub.status.busy": "2024-11-22T14:01:36.352741Z",
     "iopub.status.idle": "2024-11-22T14:01:36.369562Z",
     "shell.execute_reply": "2024-11-22T14:01:36.367954Z",
     "shell.execute_reply.started": "2024-11-22T14:01:36.353279Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<img src=\"https://miro.medium.com/v2/resize:fit:4800/format:webp/0*2CQ5PdQGvmvdg1P2.png\" width=\"400\"/>"
      ],
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Image(url='https://miro.medium.com/v2/resize:fit:4800/format:webp/0*2CQ5PdQGvmvdg1P2.png', width=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b292cbf4-8d3a-4aed-9bb2-bb0488ea1120",
   "metadata": {},
   "source": [
    "- prompt engineering\n",
    "    - 重在结构，structure/workflow/pipeline 的设计，而不只是措辞上；\n",
    "- reflexion agent: https://arxiv.org/abs/2303.11366\n",
    "    - role design\n",
    "        - generator(student) & critic(teacher)\n",
    "    - reflect on and critique its past actions,\n",
    "    - sometimes incorporating additional external information such as tool observations.\n",
    "        - execution\n",
    "-  \"System 1\" vs. \"System 2\" thinking,\n",
    "    - where System 1 is reactive or instinctive （fast thinking）\n",
    "        - 直觉的本能反应\n",
    "    - System 2 is more methodical and reflective （slow thinking）\n",
    "        - o1，learned implicit reasoing\n",
    "    - reflection can help LLM systems break out of purely System 1 \"thinking\" patterns and closer to something exhibiting System 2-like behavior.\n",
    "- reflexion agent\n",
    "    - 本质是对 messages 的操作和管理（左右互搏）\n",
    "        - generator vs. reflector\n",
    "            - 对于 generator 的输出，ai message（assistant），对于 reflector 则是 human message（user）\n",
    "            - 反之对于 reflector 的输出，ai message（assistant），对于 generator 则是 human message（user）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0ed1c886-86c3-416f-b1b1-daa0ec77b45d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:45.796015Z",
     "iopub.status.busy": "2024-11-10T14:07:45.795450Z",
     "iopub.status.idle": "2024-11-10T14:07:45.836146Z",
     "shell.execute_reply": "2024-11-10T14:07:45.834587Z",
     "shell.execute_reply.started": "2024-11-10T14:07:45.795946Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<img src=\"https://neurofied.com/wp-content/uploads/2022/05/System-12-White-1.png\" width=\"400\"/>"
      ],
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Image(url='https://neurofied.com/wp-content/uploads/2022/05/System-12-White-1.png', width=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f19dfff-2906-475d-9f91-abaf3d46d086",
   "metadata": {},
   "source": [
    "### basic reflection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2a827ef4-c14f-44c6-b74e-324500ae49d5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:45.838479Z",
     "iopub.status.busy": "2024-11-10T14:07:45.837942Z",
     "iopub.status.idle": "2024-11-10T14:07:45.879095Z",
     "shell.execute_reply": "2024-11-10T14:07:45.877507Z",
     "shell.execute_reply.started": "2024-11-10T14:07:45.838431Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<img src=\"https://blog.langchain.dev/content/images/size/w1000/2024/02/reflection.png\" width=\"400\"/>"
      ],
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Image(url='https://blog.langchain.dev/content/images/size/w1000/2024/02/reflection.png', width=400)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "880ffd58-1841-47c9-901d-5c388c095d35",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:45.881437Z",
     "iopub.status.busy": "2024-11-10T14:07:45.880918Z",
     "iopub.status.idle": "2024-11-10T14:07:45.930559Z",
     "shell.execute_reply": "2024-11-10T14:07:45.928829Z",
     "shell.execute_reply.started": "2024-11-10T14:07:45.881390Z"
    }
   },
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "assert load_dotenv()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7a759ad-ff38-4ee6-b0a5-19ceabba5636",
   "metadata": {},
   "source": [
    "#### generate"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0734bea-6486-4c40-be3f-9871faff99f9",
   "metadata": {},
   "source": [
    "- `ChatPromptTemplate` 实例化之后是 `ChatPromptValue`\n",
    "- `.stream()` 而非 `.invoke()`，长文的输出就显得没有那么耗时；\n",
    "- system prompt 不属于 messages\n",
    "    - messages 意味着是对话式的，一问一答的方式；"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7e723f77-8360-4ab0-a670-b0ee6a6c03b5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:45.936563Z",
     "iopub.status.busy": "2024-11-10T14:07:45.936026Z",
     "iopub.status.idle": "2024-11-10T14:07:47.118276Z",
     "shell.execute_reply": "2024-11-10T14:07:47.116673Z",
     "shell.execute_reply.started": "2024-11-10T14:07:45.936516Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain_core.messages import AIMessage, BaseMessage, HumanMessage\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain_openai import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "87523a51-9432-4162-9c2f-9ec72c6763ed",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.119185Z",
     "iopub.status.busy": "2024-11-10T14:07:47.118969Z",
     "iopub.status.idle": "2024-11-10T14:07:47.125938Z",
     "shell.execute_reply": "2024-11-10T14:07:47.124412Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.119165Z"
    }
   },
   "outputs": [],
   "source": [
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are an essay assistant tasked with writing excellent 5-paragraph essays.\"\n",
    "            \" Generate the best essay possible for the user's request.\"\n",
    "            \" If the user provides critique, respond with a revised version of your previous attempts.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a547dab9-1f55-4515-8775-5f6653d8dab2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.126763Z",
     "iopub.status.busy": "2024-11-10T14:07:47.126572Z",
     "iopub.status.idle": "2024-11-10T14:07:47.155865Z",
     "shell.execute_reply": "2024-11-10T14:07:47.154766Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.126746Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m System Message \u001b[0m================================\n",
      "\n",
      "You are an essay assistant tasked with writing excellent 5-paragraph essays. Generate the best essay possible for the user's request. If the user provides critique, respond with a revised version of your previous attempts.\n",
      "\n",
      "=============================\u001b[1m Messages Placeholder \u001b[0m=============================\n",
      "\n",
      "\u001b[33;1m\u001b[1;3m{messages}\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "prompt.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f64d5741-f9b1-4d8a-81c5-e5b9cf69738b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.156916Z",
     "iopub.status.busy": "2024-11-10T14:07:47.156725Z",
     "iopub.status.idle": "2024-11-10T14:07:47.255530Z",
     "shell.execute_reply": "2024-11-10T14:07:47.254056Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.156900Z"
    }
   },
   "outputs": [],
   "source": [
    "llm = ChatOpenAI(model='gpt-4o-2024-08-06')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "e4ce5ac0-2d1b-49eb-8968-292126888128",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.256371Z",
     "iopub.status.busy": "2024-11-10T14:07:47.256175Z",
     "iopub.status.idle": "2024-11-10T14:07:47.316848Z",
     "shell.execute_reply": "2024-11-10T14:07:47.315251Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.256354Z"
    }
   },
   "outputs": [],
   "source": [
    "generate = prompt | llm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "381f8ca4-849d-4abb-a75a-49ad8367b614",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.317677Z",
     "iopub.status.busy": "2024-11-10T14:07:47.317485Z",
     "iopub.status.idle": "2024-11-10T14:07:47.356309Z",
     "shell.execute_reply": "2024-11-10T14:07:47.354841Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.317660Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptTemplate(input_variables=['messages'], input_types={'messages': list[typing.Annotated[typing.Union[typing.Annotated[langchain_core.messages.ai.AIMessage, Tag(tag='ai')], typing.Annotated[langchain_core.messages.human.HumanMessage, Tag(tag='human')], typing.Annotated[langchain_core.messages.chat.ChatMessage, Tag(tag='chat')], typing.Annotated[langchain_core.messages.system.SystemMessage, Tag(tag='system')], typing.Annotated[langchain_core.messages.function.FunctionMessage, Tag(tag='function')], typing.Annotated[langchain_core.messages.tool.ToolMessage, Tag(tag='tool')], typing.Annotated[langchain_core.messages.ai.AIMessageChunk, Tag(tag='AIMessageChunk')], typing.Annotated[langchain_core.messages.human.HumanMessageChunk, Tag(tag='HumanMessageChunk')], typing.Annotated[langchain_core.messages.chat.ChatMessageChunk, Tag(tag='ChatMessageChunk')], typing.Annotated[langchain_core.messages.system.SystemMessageChunk, Tag(tag='SystemMessageChunk')], typing.Annotated[langchain_core.messages.function.FunctionMessageChunk, Tag(tag='FunctionMessageChunk')], typing.Annotated[langchain_core.messages.tool.ToolMessageChunk, Tag(tag='ToolMessageChunk')]], FieldInfo(annotation=NoneType, required=True, discriminator=Discriminator(discriminator=<function _get_type at 0x78d1f2bab100>, custom_error_type=None, custom_error_message=None, custom_error_context=None))]]}, partial_variables={}, messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], input_types={}, partial_variables={}, template=\"You are an essay assistant tasked with writing excellent 5-paragraph essays. Generate the best essay possible for the user's request. If the user provides critique, respond with a revised version of your previous attempts.\"), additional_kwargs={}), MessagesPlaceholder(variable_name='messages')])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "8f9537b4-b254-4380-95df-f6945729886b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.358182Z",
     "iopub.status.busy": "2024-11-10T14:07:47.357838Z",
     "iopub.status.idle": "2024-11-10T14:07:47.423700Z",
     "shell.execute_reply": "2024-11-10T14:07:47.421854Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.358152Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptValue(messages=[SystemMessage(content=\"You are an essay assistant tasked with writing excellent 5-paragraph essays. Generate the best essay possible for the user's request. If the user provides critique, respond with a revised version of your previous attempts.\", additional_kwargs={}, response_metadata={}), HumanMessage(content='write an essay on why the little prince is relevant in modern childhood', additional_kwargs={}, response_metadata={})])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt.invoke({'messages': [('human', 'write an essay on why the little prince is relevant in modern childhood')]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ed1f2f1f-f577-4591-bba0-49c94639e9ad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.425430Z",
     "iopub.status.busy": "2024-11-10T14:07:47.425113Z",
     "iopub.status.idle": "2024-11-10T14:07:47.447361Z",
     "shell.execute_reply": "2024-11-10T14:07:47.445834Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.425402Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ChatPromptValue(messages=[SystemMessage(content=\"You are an essay assistant tasked with writing excellent 5-paragraph essays. Generate the best essay possible for the user's request. If the user provides critique, respond with a revised version of your previous attempts.\", additional_kwargs={}, response_metadata={}), HumanMessage(content='write an essay on why the little prince is relevant in modern childhood', additional_kwargs={}, response_metadata={})])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt.invoke({'messages': [HumanMessage(content='write an essay on why the little prince is relevant in modern childhood')]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8c825902-1fbe-4d1f-8ef2-6366c933ff22",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:47.449469Z",
     "iopub.status.busy": "2024-11-10T14:07:47.448970Z",
     "iopub.status.idle": "2024-11-10T14:07:54.930051Z",
     "shell.execute_reply": "2024-11-10T14:07:54.928521Z",
     "shell.execute_reply.started": "2024-11-10T14:07:47.449424Z"
    }
   },
   "outputs": [],
   "source": [
    "resp = generate.invoke({'messages': \n",
    "                        [HumanMessage(content='write an essay on why the little prince is relevant in modern childhood')]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "aaacf60c-32c5-43c9-9956-ca2473475e86",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:54.932371Z",
     "iopub.status.busy": "2024-11-10T14:07:54.931773Z",
     "iopub.status.idle": "2024-11-10T14:07:54.940430Z",
     "shell.execute_reply": "2024-11-10T14:07:54.939027Z",
     "shell.execute_reply.started": "2024-11-10T14:07:54.932328Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Antoine de Saint-Exupéry's \"The Little Prince\" is a timeless tale that continues to resonate with readers of all ages, especially children. While the book was first published in 1943, its themes remain pertinent in today's rapidly changing world. The story's exploration of imagination, the value of relationships, and the critique of adult behavior offers vital life lessons that modern children can benefit from. This essay will delve into these aspects, illustrating why \"The Little Prince\" is relevant in contemporary childhood.\n",
      "\n",
      "Firstly, \"The Little Prince\" celebrates the boundless creativity and imagination inherent in children. In today's digital age, where structured activities and screen time often dominate, the book serves as a reminder of the importance of nurturing a child's imagination. The protagonist's journey across various planets and encounters with whimsical characters like the fox and the talking rose encourage children to think beyond the confines of their everyday experiences. This imaginative exploration fosters creativity, which is crucial for problem-solving and innovation, skills increasingly prioritized in the modern world.\n",
      "\n",
      "Secondly, the story underscores the significance of relationships and emotional intelligence, areas often overlooked in modern childhood. The Little Prince's interactions emphasize understanding, empathy, and the invisible bonds that connect individuals. In a time when social media can sometimes replace face-to-face interactions, these lessons are invaluable. The prince's relationship with the fox, which highlights the idea that \"you become responsible, forever, for what you have tamed,\" teaches children the importance of nurturing and maintaining relationships. This is especially relevant as they navigate friendships and family dynamics in a complex social landscape.\n",
      "\n",
      "Moreover, \"The Little Prince\" offers a poignant critique of adult behavior and societal values, prompting children to question the world around them. The various grown-ups the prince encounters, preoccupied with power, wealth, and status, serve as caricatures of adult obsessions that often overshadow what truly matters. In an era where consumerism and material success are frequently idolized, the book's message encourages children to prioritize love, kindness, and the simple joys of life. This critical thinking skill is essential for young minds as they develop their own beliefs and values.\n",
      "\n",
      "Furthermore, the story promotes introspection and philosophical inquiry, encouraging children to ponder existential questions. The Little Prince's reflections on life, death, and what it means to be truly happy provide a gentle introduction to these profound topics. This can be particularly beneficial in helping children develop resilience and emotional depth. In an unpredictable world, understanding such concepts can provide comfort and perspective, aiding children in coping with the challenges they face.\n",
      "\n",
      "In conclusion, \"The Little Prince\" remains a relevant and vital story for modern children. Its celebration of imagination, emphasis on relationships, critique of adult priorities, and encouragement of philosophical thinking offer essential life lessons. As children grow up in a fast-paced, technology-driven society, the timeless wisdom of \"The Little Prince\" can help them navigate their world with creativity, empathy, and a sense of wonder. By revisiting this classic, children can learn to cherish the simple and important aspects of life, ensuring that they grow into thoughtful and compassionate individuals.\n"
     ]
    }
   ],
   "source": [
    "print(resp.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "a6dc5bdd-dcdb-45fa-ade0-c710d48f4432",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:07:54.942325Z",
     "iopub.status.busy": "2024-11-10T14:07:54.941865Z",
     "iopub.status.idle": "2024-11-10T14:08:03.350513Z",
     "shell.execute_reply": "2024-11-10T14:08:03.348633Z",
     "shell.execute_reply.started": "2024-11-10T14:07:54.942283Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Antoine de Saint-Exupéry's \"The Little Prince\" is a timeless classic that continues to hold significant relevance in modern childhood. Although first published in 1943, its themes of innocence, imagination, and the essence of human relationships resonate as deeply today as they did over seventy years ago. The story's ability to transcend time and cultural boundaries makes it a valuable tool for imparting important life lessons to children in the contemporary world. This essay will explore three key reasons why \"The Little Prince\" remains relevant: its emphasis on the value of imagination, its exploration of essential human connections, and its critique of adult perspectives.\n",
      "\n",
      "Firstly, \"The Little Prince\" serves as a profound reminder of the value of imagination in childhood. In today's digital age, children's imaginations are often stifled by screens and structured activities. The Little Prince, with his fantastical journey across planets, encourages children to engage their creativity and explore the world with wonder. This imaginative exploration is crucial for cognitive development, as it fosters problem-solving skills and emotional intelligence. By reading the story, children are inspired to dream, create, and view the world from a perspective that values curiosity over conformity.\n",
      "\n",
      "Secondly, the book explores the importance of essential human connections, a theme that is increasingly important in today's fast-paced society. The Little Prince's journey is marked by his encounters with various characters, each representing different aspects of human nature. Through these interactions, Saint-Exupéry emphasizes the importance of relationships, love, and empathy. In a world where digital communication often replaces face-to-face interaction, \"The Little Prince\" reminds children of the irreplaceable value of genuine human bonds. The story teaches that what truly matters is invisible to the eye, a lesson on prioritizing meaningful connections over superficial ones.\n",
      "\n",
      "Lastly, \"The Little Prince\" offers a poignant critique of adult perspectives, urging children to question societal norms and values. The story highlights how adults often lose sight of what is truly important in life, becoming consumed by materialism and routine. The Little Prince’s encounters with grown-ups reveal the absurdities of adult priorities, encouraging children to maintain their sense of wonder and questioning. In a world that often pressures children to grow up too quickly, the book serves as a reminder to preserve the innocence and purity of childhood perspectives.\n",
      "\n",
      "In conclusion, \"The Little Prince\" remains profoundly relevant for modern childhood through its celebration of imagination, its emphasis on the importance of human connections, and its critique of adult mindsets. As children navigate the complexities of the modern world, Saint-Exupéry's timeless story offers guidance on maintaining a sense of wonder and prioritizing what truly matters in life. \"The Little Prince\" not only entertains but also educates, making it an invaluable addition to any child's literary journey. Through its enduring wisdom, the book continues to touch the hearts and minds of new generations, ensuring its place in the canon of essential childhood literature."
     ]
    }
   ],
   "source": [
    "essay = \"\"\n",
    "request = HumanMessage(\n",
    "    content='write an essay on why the little prince is relevant in modern childhood'\n",
    ")\n",
    "for chunk in generate.stream({'messages': [request]}):\n",
    "    print(chunk.content, end=\"\")\n",
    "    essay += chunk.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d2460af-891b-43d9-bf50-683987f93695",
   "metadata": {},
   "source": [
    "#### Reflect"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "8cfb37db-ad89-419a-9f31-ec5f251178d9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:03.353067Z",
     "iopub.status.busy": "2024-11-10T14:08:03.352508Z",
     "iopub.status.idle": "2024-11-10T14:08:03.361649Z",
     "shell.execute_reply": "2024-11-10T14:08:03.359990Z",
     "shell.execute_reply.started": "2024-11-10T14:08:03.353018Z"
    }
   },
   "outputs": [],
   "source": [
    "reflection_prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"You are a teacher grading an essay submission. Generate critique and recommendations for the user's submission.\"\n",
    "            \" Provide detailed recommendations, including requests for length, depth, style, etc.\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c047c819-7d6a-4a3c-8941-855890f988c5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:03.364219Z",
     "iopub.status.busy": "2024-11-10T14:08:03.363663Z",
     "iopub.status.idle": "2024-11-10T14:08:03.394143Z",
     "shell.execute_reply": "2024-11-10T14:08:03.392651Z",
     "shell.execute_reply.started": "2024-11-10T14:08:03.364172Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m System Message \u001b[0m================================\n",
      "\n",
      "You are a teacher grading an essay submission. Generate critique and recommendations for the user's submission. Provide detailed recommendations, including requests for length, depth, style, etc.\n",
      "\n",
      "=============================\u001b[1m Messages Placeholder \u001b[0m=============================\n",
      "\n",
      "\u001b[33;1m\u001b[1;3m{messages}\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "reflection_prompt.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "7529cbee-6024-49f6-83d4-e2c382f0ba36",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:03.396432Z",
     "iopub.status.busy": "2024-11-10T14:08:03.395916Z",
     "iopub.status.idle": "2024-11-10T14:08:03.437089Z",
     "shell.execute_reply": "2024-11-10T14:08:03.435241Z",
     "shell.execute_reply.started": "2024-11-10T14:08:03.396385Z"
    }
   },
   "outputs": [],
   "source": [
    "reflect = reflection_prompt | llm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c3c55498-0150-43ad-bad6-a364eeaa4417",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:03.439544Z",
     "iopub.status.busy": "2024-11-10T14:08:03.439017Z",
     "iopub.status.idle": "2024-11-10T14:08:03.487400Z",
     "shell.execute_reply": "2024-11-10T14:08:03.485657Z",
     "shell.execute_reply.started": "2024-11-10T14:08:03.439497Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"You are a teacher grading an essay submission. Generate critique and recommendations for the user's submission. Provide detailed recommendations, including requests for length, depth, style, etc.\", additional_kwargs={}, response_metadata={}),\n",
       " HumanMessage(content='Antoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless classic that continues to hold significant relevance in modern childhood. Although first published in 1943, its themes of innocence, imagination, and the essence of human relationships resonate as deeply today as they did over seventy years ago. The story\\'s ability to transcend time and cultural boundaries makes it a valuable tool for imparting important life lessons to children in the contemporary world. This essay will explore three key reasons why \"The Little Prince\" remains relevant: its emphasis on the value of imagination, its exploration of essential human connections, and its critique of adult perspectives.\\n\\nFirstly, \"The Little Prince\" serves as a profound reminder of the value of imagination in childhood. In today\\'s digital age, children\\'s imaginations are often stifled by screens and structured activities. The Little Prince, with his fantastical journey across planets, encourages children to engage their creativity and explore the world with wonder. This imaginative exploration is crucial for cognitive development, as it fosters problem-solving skills and emotional intelligence. By reading the story, children are inspired to dream, create, and view the world from a perspective that values curiosity over conformity.\\n\\nSecondly, the book explores the importance of essential human connections, a theme that is increasingly important in today\\'s fast-paced society. The Little Prince\\'s journey is marked by his encounters with various characters, each representing different aspects of human nature. Through these interactions, Saint-Exupéry emphasizes the importance of relationships, love, and empathy. In a world where digital communication often replaces face-to-face interaction, \"The Little Prince\" reminds children of the irreplaceable value of genuine human bonds. The story teaches that what truly matters is invisible to the eye, a lesson on prioritizing meaningful connections over superficial ones.\\n\\nLastly, \"The Little Prince\" offers a poignant critique of adult perspectives, urging children to question societal norms and values. The story highlights how adults often lose sight of what is truly important in life, becoming consumed by materialism and routine. The Little Prince’s encounters with grown-ups reveal the absurdities of adult priorities, encouraging children to maintain their sense of wonder and questioning. In a world that often pressures children to grow up too quickly, the book serves as a reminder to preserve the innocence and purity of childhood perspectives.\\n\\nIn conclusion, \"The Little Prince\" remains profoundly relevant for modern childhood through its celebration of imagination, its emphasis on the importance of human connections, and its critique of adult mindsets. As children navigate the complexities of the modern world, Saint-Exupéry\\'s timeless story offers guidance on maintaining a sense of wonder and prioritizing what truly matters in life. \"The Little Prince\" not only entertains but also educates, making it an invaluable addition to any child\\'s literary journey. Through its enduring wisdom, the book continues to touch the hearts and minds of new generations, ensuring its place in the canon of essential childhood literature.', additional_kwargs={}, response_metadata={})]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "reflection_prompt.invoke({'messages': [HumanMessage(content=essay)]}).messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "82a61982-848a-40ee-9bb2-5fe8915c4e9a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:03.494900Z",
     "iopub.status.busy": "2024-11-10T14:08:03.494372Z",
     "iopub.status.idle": "2024-11-10T14:08:11.284853Z",
     "shell.execute_reply": "2024-11-10T14:08:11.283068Z",
     "shell.execute_reply.started": "2024-11-10T14:08:03.494854Z"
    }
   },
   "outputs": [],
   "source": [
    "resp = reflect.invoke({'messages': [HumanMessage(content=essay)]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "89d4f90b-96c2-4ec5-9c7a-0f1865dbc68f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:11.287262Z",
     "iopub.status.busy": "2024-11-10T14:08:11.286727Z",
     "iopub.status.idle": "2024-11-10T14:08:11.295085Z",
     "shell.execute_reply": "2024-11-10T14:08:11.293550Z",
     "shell.execute_reply.started": "2024-11-10T14:08:11.287213Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your essay provides a thoughtful and engaging analysis of Antoine de Saint-Exupéry's \"The Little Prince,\" highlighting its enduring relevance and appeal to modern readers, particularly children. Your focus on the themes of imagination, human connection, and critique of adult perspectives is well-chosen, and you effectively articulate why these themes resonate today. However, there are areas where your essay could be strengthened to provide a more comprehensive and nuanced exploration.\n",
      "\n",
      "### Critique and Recommendations:\n",
      "\n",
      "1. **Depth of Analysis:**\n",
      "   - While you touch on the themes effectively, consider delving deeper into specific instances from the text to illustrate your points. For example, when discussing the value of imagination, you could analyze particular episodes, such as the Little Prince's encounter with the fox, to show how these moments encapsulate the theme.\n",
      "   - Explore the philosophical underpinnings of the novel. For instance, how does Saint-Exupéry’s personal history as a pilot and his philosophical views inform the narrative and its themes?\n",
      "\n",
      "2. **Cultural and Historical Context:**\n",
      "   - Including a brief discussion of the historical and cultural context of when the book was written could enrich your analysis. Consider how the events of World War II, during which the book was written, might have influenced its themes of connection and innocence.\n",
      "   - Discuss how the book has been received in various cultures and how its translation and adaptation into different media have helped maintain its relevance.\n",
      "\n",
      "3. **Modern Relevance:**\n",
      "   - While you mention the digital age, it would be beneficial to explore how \"The Little Prince\" contrasts with current trends in children's media and literature. How does it offer an alternative to digital narratives?\n",
      "   - Consider discussing the educational implications of the book in contemporary settings, such as its use in classrooms or therapeutic contexts.\n",
      "\n",
      "4. **Structure and Flow:**\n",
      "   - Your essay is well-structured, but consider adding transitional sentences at the beginning and end of each paragraph to enhance the flow between sections.\n",
      "   - The conclusion reiterates your main points effectively, but it could be strengthened by suggesting specific ways parents or educators can incorporate the lessons of \"The Little Prince\" into children's lives today.\n",
      "\n",
      "5. **Length and Style:**\n",
      "   - The essay is concise, which is a strength, but expanding on the points mentioned above could add depth without sacrificing clarity.\n",
      "   - Maintain the engaging and accessible style, but ensure that any additional analysis remains clear and focused to avoid overwhelming the reader with too much information.\n",
      "\n",
      "6. **Quotations and References:**\n",
      "   - Integrating direct quotations from the text can add authenticity and depth to your analysis. Consider including a few key quotes that encapsulate the themes you discuss.\n",
      "   - If relevant, reference scholarly analyses of \"The Little Prince\" to support your arguments and provide additional perspectives.\n",
      "\n",
      "By addressing these areas, your essay will offer a more comprehensive and nuanced exploration of \"The Little Prince,\" enhancing its appeal and educational value to modern readers. Overall, your essay is a solid foundation that, with further development, can provide deeper insights into the timeless relevance of this classic work.\n"
     ]
    }
   ],
   "source": [
    "print(resp.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "aae21e47-d4ab-4e28-ac2e-bae537a28e7d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:11.297303Z",
     "iopub.status.busy": "2024-11-10T14:08:11.296802Z",
     "iopub.status.idle": "2024-11-10T14:08:11.348686Z",
     "shell.execute_reply": "2024-11-10T14:08:11.347122Z",
     "shell.execute_reply.started": "2024-11-10T14:08:11.297258Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'human'"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "request.type"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "4c38e1e2-e04a-49e4-bc69-909302ff8285",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:11.351023Z",
     "iopub.status.busy": "2024-11-10T14:08:11.350503Z",
     "iopub.status.idle": "2024-11-10T14:08:11.395370Z",
     "shell.execute_reply": "2024-11-10T14:08:11.393875Z",
     "shell.execute_reply.started": "2024-11-10T14:08:11.350956Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"You are a teacher grading an essay submission. Generate critique and recommendations for the user's submission. Provide detailed recommendations, including requests for length, depth, style, etc.\", additional_kwargs={}, response_metadata={}),\n",
       " HumanMessage(content='write an essay on why the little prince is relevant in modern childhood', additional_kwargs={}, response_metadata={}),\n",
       " HumanMessage(content='Antoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless classic that continues to hold significant relevance in modern childhood. Although first published in 1943, its themes of innocence, imagination, and the essence of human relationships resonate as deeply today as they did over seventy years ago. The story\\'s ability to transcend time and cultural boundaries makes it a valuable tool for imparting important life lessons to children in the contemporary world. This essay will explore three key reasons why \"The Little Prince\" remains relevant: its emphasis on the value of imagination, its exploration of essential human connections, and its critique of adult perspectives.\\n\\nFirstly, \"The Little Prince\" serves as a profound reminder of the value of imagination in childhood. In today\\'s digital age, children\\'s imaginations are often stifled by screens and structured activities. The Little Prince, with his fantastical journey across planets, encourages children to engage their creativity and explore the world with wonder. This imaginative exploration is crucial for cognitive development, as it fosters problem-solving skills and emotional intelligence. By reading the story, children are inspired to dream, create, and view the world from a perspective that values curiosity over conformity.\\n\\nSecondly, the book explores the importance of essential human connections, a theme that is increasingly important in today\\'s fast-paced society. The Little Prince\\'s journey is marked by his encounters with various characters, each representing different aspects of human nature. Through these interactions, Saint-Exupéry emphasizes the importance of relationships, love, and empathy. In a world where digital communication often replaces face-to-face interaction, \"The Little Prince\" reminds children of the irreplaceable value of genuine human bonds. The story teaches that what truly matters is invisible to the eye, a lesson on prioritizing meaningful connections over superficial ones.\\n\\nLastly, \"The Little Prince\" offers a poignant critique of adult perspectives, urging children to question societal norms and values. The story highlights how adults often lose sight of what is truly important in life, becoming consumed by materialism and routine. The Little Prince’s encounters with grown-ups reveal the absurdities of adult priorities, encouraging children to maintain their sense of wonder and questioning. In a world that often pressures children to grow up too quickly, the book serves as a reminder to preserve the innocence and purity of childhood perspectives.\\n\\nIn conclusion, \"The Little Prince\" remains profoundly relevant for modern childhood through its celebration of imagination, its emphasis on the importance of human connections, and its critique of adult mindsets. As children navigate the complexities of the modern world, Saint-Exupéry\\'s timeless story offers guidance on maintaining a sense of wonder and prioritizing what truly matters in life. \"The Little Prince\" not only entertains but also educates, making it an invaluable addition to any child\\'s literary journey. Through its enduring wisdom, the book continues to touch the hearts and minds of new generations, ensuring its place in the canon of essential childhood literature.', additional_kwargs={}, response_metadata={})]"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "reflection_prompt.invoke({'messages': [request, HumanMessage(content=essay)]}).messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "9fc79528-0719-4baa-bf24-e28a734d5241",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:11.397794Z",
     "iopub.status.busy": "2024-11-10T14:08:11.397246Z",
     "iopub.status.idle": "2024-11-10T14:08:19.791422Z",
     "shell.execute_reply": "2024-11-10T14:08:19.789282Z",
     "shell.execute_reply.started": "2024-11-10T14:08:11.397746Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your essay on the relevance of \"The Little Prince\" in modern childhood is well-structured and covers three significant themes: the value of imagination, the importance of human connections, and the critique of adult perspectives. Your points are clearly articulated, and you effectively demonstrate how these themes continue to resonate in today's world. However, there are areas where the essay could be further developed to enhance its depth and impact.\n",
      "\n",
      "### Recommendations:\n",
      "\n",
      "1. **Length and Depth:**\n",
      "   - **Expand on Examples:** While you touch upon the themes, adding specific examples from the book would strengthen your argument. For instance, discuss the Little Prince's interaction with the fox to illustrate the importance of relationships and how it teaches the lesson that \"what is essential is invisible to the eye.\"\n",
      "   - **Contemporary Connections:** Consider drawing parallels between the book's themes and current issues or trends in childhood development. For instance, you could explore how modern educational practices (like play-based learning) align with the book's emphasis on imagination.\n",
      "\n",
      "2. **Style and Tone:**\n",
      "   - **Engage with the Audience:** Include rhetorical questions or personal reflections to make the essay more engaging. Encourage readers to reflect on their own experiences with imagination and human connections.\n",
      "   - **Use of Language:** While the language is mostly clear, varying sentence structure can enhance readability. Mix longer, complex sentences with shorter, impactful ones to maintain reader interest.\n",
      "\n",
      "3. **Additional Themes:**\n",
      "   - **Materialism and Consumerism:** Expand on the critique of adult perspectives by linking it to modern issues like consumerism and the pressure on children to conform to societal expectations.\n",
      "   - **Emotional Intelligence:** Delve deeper into how the story fosters emotional intelligence and empathy, which are crucial skills for children growing up in a diverse and globalized world.\n",
      "\n",
      "4. **Conclusion:**\n",
      "   - **Call to Action:** Strengthen the conclusion by suggesting practical ways parents or educators can incorporate the lessons of \"The Little Prince\" into children's lives, such as through discussions or creative activities inspired by the book.\n",
      "   - **Broader Implications:** Reflect on the broader implications of maintaining these childhood values into adulthood, ensuring that the timeless wisdom of the book continues to influence future generations.\n",
      "\n",
      "By incorporating these recommendations, your essay will not only provide a comprehensive analysis of \"The Little Prince\" but also effectively communicate its enduring relevance to modern childhood. This approach will offer a richer, more nuanced perspective that resonates with both young readers and those guiding them."
     ]
    }
   ],
   "source": [
    "reflection = ''\n",
    "for chunk in reflect.stream({'messages': [request, HumanMessage(content=essay)]}):\n",
    "    print(chunk.content, end=\"\")\n",
    "    reflection += chunk.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "843441f2-bfde-46de-a101-a4a07ad36479",
   "metadata": {},
   "source": [
    "#### Repeat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "2333e6ad-6719-4df8-aa32-856a65a9b98b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:19.794753Z",
     "iopub.status.busy": "2024-11-10T14:08:19.794195Z",
     "iopub.status.idle": "2024-11-10T14:08:19.805377Z",
     "shell.execute_reply": "2024-11-10T14:08:19.803205Z",
     "shell.execute_reply.started": "2024-11-10T14:08:19.794705Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "HumanMessage(content='write an essay on why the little prince is relevant in modern childhood', additional_kwargs={}, response_metadata={})"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "request"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c9c62714-a042-4b12-8ca9-7b8a44cd3d93",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:19.807923Z",
     "iopub.status.busy": "2024-11-10T14:08:19.807373Z",
     "iopub.status.idle": "2024-11-10T14:08:19.823458Z",
     "shell.execute_reply": "2024-11-10T14:08:19.821869Z",
     "shell.execute_reply.started": "2024-11-10T14:08:19.807874Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your essay on the relevance of \"The Little Prince\" in modern childhood is well-structured and covers three significant themes: the value of imagination, the importance of human connections, and the critique of adult perspectives. Your points are clearly articulated, and you effectively demonstrate how these themes continue to resonate in today's world. However, there are areas where the essay could be further developed to enhance its depth and impact.\n",
      "\n",
      "### Recommendations:\n",
      "\n",
      "1. **Length and Depth:**\n",
      "   - **Expand on Examples:** While you touch upon the themes, adding specific examples from the book would strengthen your argument. For instance, discuss the Little Prince's interaction with the fox to illustrate the importance of relationships and how it teaches the lesson that \"what is essential is invisible to the eye.\"\n",
      "   - **Contemporary Connections:** Consider drawing parallels between the book's themes and current issues or trends in childhood development. For instance, you could explore how modern educational practices (like play-based learning) align with the book's emphasis on imagination.\n",
      "\n",
      "2. **Style and Tone:**\n",
      "   - **Engage with the Audience:** Include rhetorical questions or personal reflections to make the essay more engaging. Encourage readers to reflect on their own experiences with imagination and human connections.\n",
      "   - **Use of Language:** While the language is mostly clear, varying sentence structure can enhance readability. Mix longer, complex sentences with shorter, impactful ones to maintain reader interest.\n",
      "\n",
      "3. **Additional Themes:**\n",
      "   - **Materialism and Consumerism:** Expand on the critique of adult perspectives by linking it to modern issues like consumerism and the pressure on children to conform to societal expectations.\n",
      "   - **Emotional Intelligence:** Delve deeper into how the story fosters emotional intelligence and empathy, which are crucial skills for children growing up in a diverse and globalized world.\n",
      "\n",
      "4. **Conclusion:**\n",
      "   - **Call to Action:** Strengthen the conclusion by suggesting practical ways parents or educators can incorporate the lessons of \"The Little Prince\" into children's lives, such as through discussions or creative activities inspired by the book.\n",
      "   - **Broader Implications:** Reflect on the broader implications of maintaining these childhood values into adulthood, ensuring that the timeless wisdom of the book continues to influence future generations.\n",
      "\n",
      "By incorporating these recommendations, your essay will not only provide a comprehensive analysis of \"The Little Prince\" but also effectively communicate its enduring relevance to modern childhood. This approach will offer a richer, more nuanced perspective that resonates with both young readers and those guiding them.\n"
     ]
    }
   ],
   "source": [
    "print(reflection)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "515e60c0-d92c-438a-b96f-0f5dbf657702",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:19.826061Z",
     "iopub.status.busy": "2024-11-10T14:08:19.825509Z",
     "iopub.status.idle": "2024-11-10T14:08:27.692083Z",
     "shell.execute_reply": "2024-11-10T14:08:27.690043Z",
     "shell.execute_reply.started": "2024-11-10T14:08:19.826014Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Antoine de Saint-Exupéry's \"The Little Prince\" is a timeless narrative that maintains its profound relevance in modern childhood. Despite being over seventy years old, the book's themes of imagination, the essence of human connections, and its critique of adult perspectives continue to resonate deeply with today's readers. As children grow up in an increasingly fast-paced, digital world, \"The Little Prince\" offers invaluable lessons that nurture their development. This essay will delve into specific examples from the book to explore its relevance, draw contemporary connections, and suggest practical ways to incorporate its lessons into children's lives.\n",
      "\n",
      "Firstly, \"The Little Prince\" emphasizes the value of imagination, which is essential for children's cognitive and emotional development. In a world where screens often dominate children's attention, the book encourages imaginative exploration through its fantastical narrative. The Little Prince’s journey across different planets, each with its own unique inhabitants, serves as an invitation for children to dream and create. For example, the Little Prince's interaction with the rose on his home planet illustrates the depth of imagination required to appreciate beauty and uniqueness. Play-based learning, a modern educational practice that aligns with this theme, supports children's creativity and problem-solving skills. By fostering an environment where imagination is valued, children can learn to approach challenges with curiosity and innovation.\n",
      "\n",
      "Secondly, the book poignantly explores the importance of human connections, a theme increasingly crucial in today's digital society. The Little Prince's encounter with the fox is a pivotal moment that underscores the significance of relationships. Through the fox, the Little Prince learns that \"what is essential is invisible to the eye,\" highlighting the value of love, trust, and empathy. In an era where digital communication often overshadows face-to-face interactions, these lessons remind children of the irreplaceable value of genuine human bonds. Encouraging children to build meaningful relationships through shared experiences and empathy fosters emotional intelligence, a critical skill in our diverse and globalized world.\n",
      "\n",
      "Moreover, \"The Little Prince\" offers a critique of adult perspectives, urging children to question societal norms and values. The story reveals how adults often become consumed by materialism and lose sight of what truly matters. For instance, the Little Prince's visit to the businessman’s planet, where the man is obsessed with counting stars as his possessions, serves as a satire of adult priorities. This critique is particularly relevant today, as children face pressures to conform to societal expectations from a young age. By encouraging children to preserve their sense of wonder and questioning, the book advocates for a world where inner values take precedence over materialistic pursuits.\n",
      "\n",
      "In conclusion, \"The Little Prince\" remains profoundly relevant for modern childhood through its celebration of imagination, its emphasis on essential human connections, and its critique of adult mindsets. To incorporate these lessons into children's lives, parents and educators can engage children in discussions about the book's themes, encouraging them to reflect on their own experiences. Creative activities inspired by the story, such as drawing or storytelling, can also help children internalize its messages. By maintaining the timeless wisdom of the book, we can ensure that future generations grow up with the values of imagination, empathy, and introspection. Through its enduring insights, \"The Little Prince\" continues to touch the hearts and minds of new readers, making it an essential part of any child's literary journey."
     ]
    }
   ],
   "source": [
    "for chunk in generate.stream(\n",
    "    {\"messages\": [request, AIMessage(content=essay), HumanMessage(content=reflection)]}\n",
    "):\n",
    "    print(chunk.content, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc352865-3b06-4e30-b8a5-16a19ef2c68c",
   "metadata": {},
   "source": [
    "#### construct Graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "0f88da51-96d7-40d9-9093-3bc7c3f93bc6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:27.694446Z",
     "iopub.status.busy": "2024-11-10T14:08:27.693914Z",
     "iopub.status.idle": "2024-11-10T14:08:27.774662Z",
     "shell.execute_reply": "2024-11-10T14:08:27.773097Z",
     "shell.execute_reply.started": "2024-11-10T14:08:27.694398Z"
    }
   },
   "outputs": [],
   "source": [
    "from typing import Annotated, List, Sequence\n",
    "from langgraph.graph import END, StateGraph, START\n",
    "from langgraph.graph.message import add_messages\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from typing_extensions import TypedDict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "b43700fb-96d4-4f2f-a334-d7cbb82a238a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:27.776933Z",
     "iopub.status.busy": "2024-11-10T14:08:27.776467Z",
     "iopub.status.idle": "2024-11-10T14:08:27.784365Z",
     "shell.execute_reply": "2024-11-10T14:08:27.782694Z",
     "shell.execute_reply.started": "2024-11-10T14:08:27.776893Z"
    }
   },
   "outputs": [],
   "source": [
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "63af493a-23fc-4a66-9a50-675e06dde13e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:27.786559Z",
     "iopub.status.busy": "2024-11-10T14:08:27.786079Z",
     "iopub.status.idle": "2024-11-10T14:08:27.845782Z",
     "shell.execute_reply": "2024-11-10T14:08:27.843979Z",
     "shell.execute_reply.started": "2024-11-10T14:08:27.786516Z"
    }
   },
   "outputs": [],
   "source": [
    "async def generation_node(state: State) -> State:\n",
    "    print('generation node', [msg.type for msg in state['messages']])\n",
    "    return {\"messages\": [await generate.ainvoke(state[\"messages\"])]}\n",
    "\n",
    "\n",
    "async def reflection_node(state: State) -> State:\n",
    "    print('reflection node raw', [msg.type for msg in state['messages']])\n",
    "    # Other messages we need to adjust\n",
    "    cls_map = {\"ai\": HumanMessage, \"human\": AIMessage}\n",
    "    \n",
    "    # First message is the original user request. We hold it the same for all nodes\n",
    "    translated = [state[\"messages\"][0]] + [\n",
    "        cls_map[msg.type](content=msg.content) for msg in state[\"messages\"][1:]\n",
    "    ]\n",
    "    print('reflection node processed', [msg.type for msg in translated])\n",
    "    res = await reflect.ainvoke(translated)\n",
    "    # We treat the output of this as human feedback for the generator\n",
    "    return {\"messages\": [HumanMessage(content=res.content)]}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3273aefc-2813-40f4-b9b1-8cbff401ec57",
   "metadata": {},
   "source": [
    "- messages\n",
    "    - round 1\n",
    "        - generate\n",
    "            - input: [`human`]\n",
    "            - output: [`human`, `ai`]\n",
    "        - reflect\n",
    "            - input: [`human`, `ai`] -> [`human`, `human`]\n",
    "            - output: [`human`, `ai`, `human`]\n",
    "                - 问题，回答，反思\n",
    "    - round 2\n",
    "        - generate\n",
    "            - input: [`human`, `ai`, `human`]\n",
    "            - output: [`human`, `ai`, `human`, `ai`]\n",
    "                - 问题，回答，反思，改进后的回答\n",
    "        - reflect\n",
    "            - input: [`human`, `ai`, `human`, `ai`] => [`human`, `human`, `ai`, `human`]\n",
    "            - output: [`human`, `ai`, `human`, `ai`, `human`]\n",
    "    - round 3\n",
    "        - generate\n",
    "            - input: [`human`, `ai`, `human`, `ai`, `human`] \n",
    "            - output: [`human`, `ai`, `human`, `ai`, `human`, `ai`]\n",
    "        - reflect\n",
    "            - input: [`human`, `ai`, `human`, `ai`, `human`, `ai`] => [`human`, `human`, `ai`, `human`, `ai`, `human`]\n",
    "            - output: [`human`, `ai`, `human`, `ai`, `human`, `ai`, `human`]\n",
    "    - round4\n",
    "        - generate\n",
    "            - input: [`human`, `ai`, `human`, `ai`, `human`, `ai`, `human`]\n",
    "            - output: [`human`, `ai`, `human`, `ai`, `human`, `ai`, `human`, `ai`]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "d3000318-8e4a-4cef-9624-6e5eed1b0d71",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:27.848186Z",
     "iopub.status.busy": "2024-11-10T14:08:27.847646Z",
     "iopub.status.idle": "2024-11-10T14:08:27.891448Z",
     "shell.execute_reply": "2024-11-10T14:08:27.889845Z",
     "shell.execute_reply.started": "2024-11-10T14:08:27.848140Z"
    }
   },
   "outputs": [],
   "source": [
    "builder = StateGraph(State)\n",
    "builder.add_node(\"generate\", generation_node)\n",
    "builder.add_node(\"reflect\", reflection_node)\n",
    "builder.add_edge(START, \"generate\")\n",
    "\n",
    "def should_continue(state: State):\n",
    "    if len(state[\"messages\"]) > 6:\n",
    "        # End after 3 iterations\n",
    "        return END\n",
    "    return \"reflect\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "f36abc64-28db-416b-a369-cda6ee328347",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:27.894064Z",
     "iopub.status.busy": "2024-11-10T14:08:27.893512Z",
     "iopub.status.idle": "2024-11-10T14:08:27.937487Z",
     "shell.execute_reply": "2024-11-10T14:08:27.935465Z",
     "shell.execute_reply.started": "2024-11-10T14:08:27.894015Z"
    }
   },
   "outputs": [],
   "source": [
    "builder.add_conditional_edges(\"generate\", should_continue)\n",
    "builder.add_edge(\"reflect\", \"generate\")\n",
    "memory = MemorySaver()\n",
    "graph = builder.compile(checkpointer=memory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "cc38f43d-ec79-41be-8d6a-b0adb5355789",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:27.940015Z",
     "iopub.status.busy": "2024-11-10T14:08:27.939467Z",
     "iopub.status.idle": "2024-11-10T14:08:29.248152Z",
     "shell.execute_reply": "2024-11-10T14:08:29.246682Z",
     "shell.execute_reply.started": "2024-11-10T14:08:27.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AHRd1etDTgZDBEyCFg2bHG0Na0e8AO5fVfO5d0hXlsxFrUxq5ngIiLygULmNFaf1DYFjKYPG5GcDlEtqpHI8D3t3AnZTSK1NdVE3pm0nYq3tV6M+KeE/d8X1U9qvRnxTwn7vi+qrSi7dYxt+eMpvO1Vvar0Z8U8J+74vqp7VejPinhP3fF9VWlE6xjb88ZLztVb2q9GfFPCfu+L6qe1Xoz4p4T93xfVVpROsY2/PGS87VW9qvRnxTwn7vi+qntV6M+KeE/d8X1VaUTrGNvzxkvO1HYfTuK09HJHi8bUxrJNudtSBsQdsNhvygb7BSKIuNVU1TeqbygREVQREQEREBERAREQEREBERAREQEREH//Z",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image, display\n",
    "\n",
    "try:\n",
    "    display(Image(graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "70d2c656-1aa5-4bb0-80c0-fa0877dd1330",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:29.250476Z",
     "iopub.status.busy": "2024-11-10T14:08:29.249957Z",
     "iopub.status.idle": "2024-11-10T14:08:29.258314Z",
     "shell.execute_reply": "2024-11-10T14:08:29.256283Z",
     "shell.execute_reply.started": "2024-11-10T14:08:29.250430Z"
    }
   },
   "outputs": [],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"1\"}}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "0173ada8-d67e-4751-b89d-1362cd2cd076",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:08:29.261368Z",
     "iopub.status.busy": "2024-11-10T14:08:29.260803Z",
     "iopub.status.idle": "2024-11-10T14:09:37.869199Z",
     "shell.execute_reply": "2024-11-10T14:09:37.867190Z",
     "shell.execute_reply.started": "2024-11-10T14:08:29.261320Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "generation node ['human']\n",
      "{'generate': {'messages': [AIMessage(content='Antoine de Saint-Exupéry\\'s timeless masterpiece, \"The Little Prince,\" continues to resonate profoundly with readers across the globe, transcending cultural and generational boundaries. Written in 1943, the novella’s exploration of human nature, relationships, and the essence of life remains remarkably relevant in today\\'s world. Its enduring topicality lies in its poignant message about the importance of seeing with the heart, the critique of adult preoccupations, and the celebration of childlike wonder.\\n\\nAt the core of \"The Little Prince\" is the exploration of human relationships and the recognition of essential truths that are often invisible to the eye. In a world increasingly dominated by technology and superficial connections, the novella\\'s message about the importance of genuine relationships is more pertinent than ever. The Little Prince\\'s encounters with various characters, such as the fox, emphasize the value of meaningful bonds. The fox\\'s lesson, \"One sees clearly only with the heart. What is essential is invisible to the eye,\" reminds us to prioritize empathy, love, and understanding over materialism and appearances. This message is especially crucial in modern life, where social media and digital interactions often overshadow genuine human connection.\\n\\nFurthermore, \"The Little Prince\" offers a poignant critique of adult preoccupations, highlighting the absurdity of many societal norms and the loss of innocence as people age. The adult characters in the novella, such as the businessman obsessed with counting stars and the king who rules over nothing, symbolize the misguided priorities prevalent in contemporary society. These characters reflect the tendency of adults to focus on wealth, power, and status at the expense of inner happiness and fulfillment. In an era where consumerism and careerism often dictate life choices, the book encourages a reevaluation of what truly matters and a return to the simplicity and sincerity of childhood.\\n\\nIn addition, the novella celebrates childlike wonder and imagination, advocating for a perspective that values curiosity and creativity. The Little Prince’s journey across different planets and his observations of their inhabitants illustrate the richness of seeing the world through a child\\'s eyes. Modern life, characterized by rapid technological advancements and information overload, often stifles creativity. The novella\\'s emphasis on maintaining a sense of wonder serves as a reminder to nurture imagination and remain open to possibilities, fostering innovation and personal growth.\\n\\nMoreover, \"The Little Prince\" addresses themes of loneliness and isolation, which are increasingly relevant in today\\'s fast-paced world. Despite living in an era of unprecedented connectivity, many individuals experience profound loneliness and disconnection. The Little Prince’s travels and his longing for his rose underscore the universal human desire for companionship and belonging. This theme encourages readers to seek deeper connections with others and to appreciate the beauty of relationships, fostering a sense of community and shared humanity.\\n\\nIn conclusion, \"The Little Prince\" remains a timeless exploration of the human condition, offering valuable insights into relationships, priorities, and the essence of life. Its message of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder is deeply relevant in today\\'s world. As we navigate the complexities of modern life, the novella serves as a gentle reminder to cherish genuine connections, reevaluate our priorities, and embrace the wonder of existence. Through its enduring wisdom, \"The Little Prince\" continues to inspire readers to live authentically and to view the world with both curiosity and compassion.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 666, 'prompt_tokens': 69, 'total_tokens': 735, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_9e15ccd6a4', 'finish_reason': 'stop', 'logprobs': None}, id='run-6b34da98-75c4-4da9-86c0-5c4d9451bd62-0', usage_metadata={'input_tokens': 69, 'output_tokens': 666, 'total_tokens': 735})]}}\n",
      "---\n",
      "reflection node raw ['human', 'ai']\n",
      "reflection node processed ['human', 'human']\n",
      "{'reflect': {'messages': [HumanMessage(content='Your essay on the topicality of \"The Little Prince\" and its message in modern life provides a thoughtful analysis of the themes presented in Antoine de Saint-Exupéry\\'s work. It effectively highlights the relevance of the novella\\'s messages about human relationships, adult preoccupations, and the value of childlike wonder. Here are some critiques and recommendations to enhance your essay:\\n\\n### Strengths:\\n1. **Clear Structure**: The essay is well-organized, with each paragraph focusing on a distinct theme, such as human relationships, adult preoccupations, and childlike wonder.\\n2. **Relevant Themes**: You have successfully identified key themes in \"The Little Prince\" that hold relevance in contemporary society.\\n3. **Concise Language**: The language used is clear and concise, making the essay easy to read and understand.\\n\\n### Recommendations:\\n1. **Depth of Analysis**: While the essay touches upon critical themes, it could benefit from a deeper analysis. Consider expanding on how each theme specifically manifests in today\\'s society. For instance, provide examples of how social media affects genuine human connections or how consumerism is reflected in daily life.\\n   \\n2. **Use of Quotations**: You effectively use a quotation from the fox, but incorporating additional quotes from the novella could strengthen your arguments and provide textual evidence for your claims.\\n\\n3. **Length**: The essay is relatively brief. Expanding it to around 1,200 words could allow for more comprehensive exploration of each theme. Additional paragraphs could delve into more nuanced aspects of each topic or introduce new themes, such as the idea of responsibility and its relevance today.\\n\\n4. **Style and Tone**: While the essay maintains a formal tone, consider varying sentence structure to enhance readability and engagement. Adding rhetorical questions or vivid imagery could also capture the reader\\'s interest more effectively.\\n\\n5. **Connections to Modern Life**: While the essay mentions modern life, providing specific examples or case studies would make the discussion more concrete. For instance, discuss how children today perceive technology or the impact of the educational system on creativity and imagination.\\n\\n6. **Conclusion**: The conclusion is succinct but could be more impactful by summarizing the key points and reiterating their significance in today\\'s context. Perhaps suggest practical ways readers can apply the lessons of \"The Little Prince\" in their own lives.\\n\\nOverall, your essay offers a solid foundation for discussing the enduring relevance of \"The Little Prince.\" By incorporating more detailed analysis, examples, and stylistic variety, you can elevate your discussion to a more nuanced and engaging level.', additional_kwargs={}, response_metadata={}, id='af83db8b-f6a0-4548-b544-7518cd89a543')]}}\n",
      "---\n",
      "generation node ['human', 'ai', 'human']\n",
      "{'generate': {'messages': [AIMessage(content='Antoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless literary work that continues to captivate audiences across generations with its profound exploration of human nature, relationships, and the essence of life. Written in 1943, the novella remains strikingly relevant in today\\'s world, offering invaluable insights into the importance of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder. Its message resonates in our modern era, where technology, consumerism, and a fast-paced lifestyle threaten to overshadow genuine human connections and creativity.\\n\\nAt the heart of \"The Little Prince\" is its exploration of human relationships and the recognition of essential truths that are often invisible to the eye. In an age dominated by digital interactions and social media, the novella\\'s message about the value of authentic relationships is more pertinent than ever. The Little Prince\\'s encounter with the fox emphasizes the significance of meaningful bonds, encapsulated in the iconic lesson, \"One sees clearly only with the heart. What is essential is invisible to the eye.\" In contemporary society, where online personas and curated images often mask true emotions and connections, this message encourages us to prioritize empathy, love, and understanding. Social media platforms, while connecting us globally, can also lead to feelings of isolation and superficiality, making the novella\\'s call for genuine relationships a crucial reminder of what truly matters.\\n\\nFurthermore, \"The Little Prince\" offers a poignant critique of adult preoccupations, highlighting the absurdity of many societal norms and the loss of innocence as people age. The adult characters in the novella, such as the businessman obsessed with counting stars and the king who rules over nothing, symbolize the misguided priorities prevalent in contemporary society. These characters reflect the tendency of adults to focus on wealth, power, and status at the expense of inner happiness and fulfillment. In an era where consumerism and careerism often dictate life choices, the book encourages a reevaluation of what truly matters. For instance, the constant pursuit of material success often leads to stress and dissatisfaction, as seen in modern issues like work-life imbalance and burnout. \"The Little Prince\" invites us to question these societal pressures, advocating for a return to the simplicity and sincerity of childhood.\\n\\nIn addition, the novella celebrates childlike wonder and imagination, advocating for a perspective that values curiosity and creativity. The Little Prince’s journey across different planets and his observations of their inhabitants illustrate the richness of seeing the world through a child\\'s eyes. Modern life, characterized by rapid technological advancements and information overload, often stifles creativity. In educational systems focused on standardized testing and rote learning, children\\'s natural curiosity can be overshadowed by the pressure to conform and perform. The novella\\'s emphasis on maintaining a sense of wonder serves as a reminder to nurture imagination and remain open to possibilities, fostering innovation and personal growth. The importance of preserving creativity in children is evident in initiatives like STEM education and arts programs, which strive to balance analytical skills with creative thinking.\\n\\nMoreover, \"The Little Prince\" addresses themes of loneliness and isolation, which are increasingly relevant in today\\'s fast-paced world. Despite living in an era of unprecedented connectivity, many individuals experience profound loneliness and disconnection. The Little Prince’s travels and his longing for his rose underscore the universal human desire for companionship and belonging. This theme encourages readers to seek deeper connections with others and to appreciate the beauty of relationships, fostering a sense of community and shared humanity. In modern times, movements promoting mental health awareness and community engagement highlight the need for connection in combating loneliness.\\n\\nIn conclusion, \"The Little Prince\" remains a timeless exploration of the human condition, offering valuable insights into relationships, priorities, and the essence of life. Its message of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder is deeply relevant in today\\'s world. As we navigate the complexities of modern life, the novella serves as a gentle reminder to cherish genuine connections, reevaluate our priorities, and embrace the wonder of existence. By incorporating its lessons into our lives, we can foster a more compassionate and fulfilling world. Through its enduring wisdom, \"The Little Prince\" continues to inspire readers to live authentically and to view the world with both curiosity and compassion.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 843, 'prompt_tokens': 1257, 'total_tokens': 2100, 'prompt_tokens_details': {'cached_tokens': 0, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_45cf54deae', 'finish_reason': 'stop', 'logprobs': None}, id='run-d5ad0e2b-abf5-4678-a4cf-cf868dd28c0f-0', usage_metadata={'input_tokens': 1257, 'output_tokens': 843, 'total_tokens': 2100})]}}\n",
      "---\n",
      "reflection node raw ['human', 'ai', 'human', 'ai']\n",
      "reflection node processed ['human', 'human', 'ai', 'human']\n",
      "{'reflect': {'messages': [HumanMessage(content='Your revised essay on the topicality of \"The Little Prince\" shows significant improvement, especially in terms of depth and relevance to modern society. You\\'ve successfully integrated more specific examples and a nuanced analysis, which enriches the discussion. Here are some critiques and further recommendations to refine your essay:\\n\\n### Strengths:\\n1. **Enhanced Depth**: You\\'ve delved deeper into the themes, particularly in relation to contemporary issues like social media\\'s impact on relationships and the pressures of consumerism.\\n2. **Relevant Examples**: The inclusion of examples such as STEM education and mental health awareness initiatives adds concrete evidence to support your arguments.\\n3. **Coherent Structure**: The essay maintains a logical flow, with each paragraph building on the previous one to develop a comprehensive argument.\\n\\n### Recommendations:\\n1. **Expand on Technological Impact**: While you mention technology and digital interactions, consider exploring other aspects, such as how virtual reality or artificial intelligence might further complicate genuine human connections or creativity.\\n\\n2. **Incorporate More Quotes**: You effectively used one quote from the novella. Including additional quotes or references to specific scenes can strengthen your arguments and provide further textual support.\\n\\n3. **Length and Depth**: While the essay is comprehensive, expanding it slightly could allow for a deeper dive into each theme. Aim for around 1,200 to 1,500 words to explore additional facets or provide more detailed examples.\\n\\n4. **Style and Engagement**: The essay is well-written, but varying the sentence structure and incorporating rhetorical questions or anecdotes could make it more engaging. Consider starting with a compelling anecdote or question to draw readers in from the beginning.\\n\\n5. **Address Potential Counterarguments**: Briefly address potential counterarguments or limitations of your analysis. For instance, consider acknowledging that while technology can lead to isolation, it also offers platforms for new forms of connection and creativity.\\n\\n6. **Conclusion Enhancement**: Strengthen the conclusion by summarizing key points more succinctly and suggesting practical ways readers might apply the novella\\'s lessons in their daily lives, perhaps through mindfulness practices or prioritizing face-to-face interactions.\\n\\n7. **Proofread for Clarity**: Ensure that the language is clear and free of any grammatical errors. Reading the essay aloud can help catch awkward phrasing or run-on sentences.\\n\\nOverall, your essay is insightful and well-structured, with a strong grasp of how \"The Little Prince\" remains relevant today. By incorporating these recommendations, you can further enhance its depth and engagement, making it an even more compelling read.', additional_kwargs={}, response_metadata={}, id='335e5a7f-7101-4f8b-8e1f-bfe67bf41d7b')]}}\n",
      "---\n",
      "generation node ['human', 'ai', 'human', 'ai', 'human']\n",
      "{'generate': {'messages': [AIMessage(content='Antoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless literary work that continues to captivate audiences across generations with its profound exploration of human nature, relationships, and the essence of life. Written in 1943, the novella remains strikingly relevant in today\\'s world, offering invaluable insights into the importance of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder. Its message resonates in our modern era, where technology, consumerism, and a fast-paced lifestyle threaten to overshadow genuine human connections and creativity.\\n\\nAt the heart of \"The Little Prince\" is its exploration of human relationships and the recognition of essential truths that are often invisible to the eye. In an age dominated by digital interactions and social media, the novella\\'s message about the value of authentic relationships is more pertinent than ever. The Little Prince\\'s encounter with the fox emphasizes the significance of meaningful bonds, encapsulated in the iconic lesson, \"One sees clearly only with the heart. What is essential is invisible to the eye.\" In contemporary society, where online personas and curated images often mask true emotions and connections, this message encourages us to prioritize empathy, love, and understanding. Social media platforms, while connecting us globally, can also lead to feelings of isolation and superficiality, making the novella\\'s call for genuine relationships a crucial reminder of what truly matters.\\n\\nFurthermore, \"The Little Prince\" offers a poignant critique of adult preoccupations, highlighting the absurdity of many societal norms and the loss of innocence as people age. The adult characters in the novella, such as the businessman obsessed with counting stars and the king who rules over nothing, symbolize the misguided priorities prevalent in contemporary society. These characters reflect the tendency of adults to focus on wealth, power, and status at the expense of inner happiness and fulfillment. In an era where consumerism and careerism often dictate life choices, the book encourages a reevaluation of what truly matters. For instance, the constant pursuit of material success often leads to stress and dissatisfaction, as seen in modern issues like work-life imbalance and burnout. \"The Little Prince\" invites us to question these societal pressures, advocating for a return to the simplicity and sincerity of childhood.\\n\\nIn addition, the novella celebrates childlike wonder and imagination, advocating for a perspective that values curiosity and creativity. The Little Prince’s journey across different planets and his observations of their inhabitants illustrate the richness of seeing the world through a child\\'s eyes. Modern life, characterized by rapid technological advancements and information overload, often stifles creativity. In educational systems focused on standardized testing and rote learning, children\\'s natural curiosity can be overshadowed by the pressure to conform and perform. The novella\\'s emphasis on maintaining a sense of wonder serves as a reminder to nurture imagination and remain open to possibilities, fostering innovation and personal growth. The importance of preserving creativity in children is evident in initiatives like STEM education and arts programs, which strive to balance analytical skills with creative thinking.\\n\\nMoreover, \"The Little Prince\" addresses themes of loneliness and isolation, which are increasingly relevant in today\\'s fast-paced world. Despite living in an era of unprecedented connectivity, many individuals experience profound loneliness and disconnection. The Little Prince’s travels and his longing for his rose underscore the universal human desire for companionship and belonging. This theme encourages readers to seek deeper connections with others and to appreciate the beauty of relationships, fostering a sense of community and shared humanity. In modern times, movements promoting mental health awareness and community engagement highlight the need for connection in combating loneliness.\\n\\nIn conclusion, \"The Little Prince\" remains a timeless exploration of the human condition, offering valuable insights into relationships, priorities, and the essence of life. Its message of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder is deeply relevant in today\\'s world. As we navigate the complexities of modern life, the novella serves as a gentle reminder to cherish genuine connections, reevaluate our priorities, and embrace the wonder of existence. By incorporating its lessons into our lives, we can foster a more compassionate and fulfilling world. Through its enduring wisdom, \"The Little Prince\" continues to inspire readers to live authentically and to view the world with both curiosity and compassion.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 843, 'prompt_tokens': 2619, 'total_tokens': 3462, 'prompt_tokens_details': {'cached_tokens': 1920, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_45cf54deae', 'finish_reason': 'stop', 'logprobs': None}, id='run-d66c810a-5d3a-4410-bdd5-8ce78276b03c-0', usage_metadata={'input_tokens': 2619, 'output_tokens': 843, 'total_tokens': 3462})]}}\n",
      "---\n",
      "reflection node raw ['human', 'ai', 'human', 'ai', 'human', 'ai']\n",
      "reflection node processed ['human', 'human', 'ai', 'human', 'ai', 'human']\n",
      "{'reflect': {'messages': [HumanMessage(content='Your essay on \"The Little Prince\" provides a comprehensive exploration of the novella\\'s themes and their relevance to modern life. It effectively connects the timeless messages of the story with contemporary issues such as technology\\'s impact on relationships, consumerism, and the loss of creativity. Here are some critiques and recommendations to further enhance your essay:\\n\\n### Strengths:\\n1. **Thematic Analysis**: You have identified and thoroughly discussed key themes, such as the value of authentic relationships, the critique of adult priorities, and the celebration of childlike wonder.\\n2. **Modern Relevance**: The essay successfully connects the novella\\'s messages to current societal challenges, making the analysis timely and relatable.\\n3. **Structured Argument**: The essay is well-organized, with each paragraph logically building on the last, leading to a cohesive narrative.\\n\\n### Recommendations:\\n1. **Use of Additional Quotes**: While you use the fox\\'s quote effectively, incorporating more quotations or specific dialogues from the novella could provide stronger textual support for your arguments. Consider referencing specific interactions between the Little Prince and other characters to illustrate your points.\\n\\n2. **Additional Examples**: While you mention initiatives like STEM education and mental health awareness, you could further expand on these examples or introduce others. For instance, discuss specific programs or movements that encourage creativity in children or combat loneliness in adults.\\n\\n3. **Deeper Counterpoints**: Briefly consider any counterarguments or alternative interpretations of the novella\\'s themes. For instance, while technology can lead to isolation, it also offers opportunities for new forms of connection and creativity that could be acknowledged.\\n\\n4. **Engagement and Style**: To make the essay more engaging, consider varying sentence structure and incorporating rhetorical questions or personal reflections. This can help maintain reader interest and enhance the essay\\'s narrative quality.\\n\\n5. **Conclusion Enhancement**: The conclusion succinctly wraps up the essay, but you might strengthen it by suggesting practical applications of the novella\\'s lessons in daily life. Encourage readers to engage in activities that foster genuine connections or creativity.\\n\\n6. **Proofreading**: Ensure the essay is free from grammatical errors and awkward phrasing. Reading the essay aloud or having someone else review it can help catch these.\\n\\nOverall, your essay is insightful and well-constructed, with a clear understanding of how \"The Little Prince\" remains relevant today. By incorporating these recommendations, you can further enrich the depth and engagement of your analysis, making it an even more compelling and thought-provoking read.', additional_kwargs={}, response_metadata={}, id='db22af60-951c-475b-83e1-3e4ea633235b')]}}\n",
      "---\n",
      "generation node ['human', 'ai', 'human', 'ai', 'human', 'ai', 'human']\n",
      "{'generate': {'messages': [AIMessage(content='Antoine de Saint-Exupéry\\'s \"The Little Prince\" is a timeless literary work that continues to captivate audiences across generations with its profound exploration of human nature, relationships, and the essence of life. Written in 1943, the novella remains strikingly relevant in today\\'s world, offering invaluable insights into the importance of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder. Its message resonates in our modern era, where technology, consumerism, and a fast-paced lifestyle threaten to overshadow genuine human connections and creativity.\\n\\nAt the heart of \"The Little Prince\" is its exploration of human relationships and the recognition of essential truths that are often invisible to the eye. In an age dominated by digital interactions and social media, the novella\\'s message about the value of authentic relationships is more pertinent than ever. The Little Prince\\'s encounter with the fox emphasizes the significance of meaningful bonds, encapsulated in the iconic lesson, \"One sees clearly only with the heart. What is essential is invisible to the eye.\" This sentiment challenges the digital façade of social media, where curated images and online personas often mask true emotions and connections. While platforms like Facebook and Instagram connect us globally, they can also foster feelings of isolation and superficiality, underscoring the novella\\'s call for genuine relationships as a crucial reminder of what truly matters.\\n\\nFurthermore, \"The Little Prince\" offers a poignant critique of adult preoccupations, highlighting the absurdity of many societal norms and the loss of innocence as people age. Adult characters in the novella, such as the businessman obsessed with counting stars and the king who rules over nothing, symbolize the misguided priorities prevalent in contemporary society. These characters reflect the tendency of adults to focus on wealth, power, and status at the expense of inner happiness and fulfillment. In an era where consumerism and careerism often dictate life choices, the book encourages a reevaluation of what truly matters. For example, the relentless pursuit of material success often leads to stress and dissatisfaction, manifesting in modern issues like work-life imbalance and burnout. \"The Little Prince\" invites us to question these societal pressures, advocating for a return to the simplicity and sincerity of childhood.\\n\\nIn addition, the novella celebrates childlike wonder and imagination, advocating for a perspective that values curiosity and creativity. The Little Prince’s journey across different planets and his observations of their inhabitants illustrate the richness of seeing the world through a child\\'s eyes. Modern life, characterized by rapid technological advancements and information overload, often stifles creativity. Educational systems focused on standardized testing and rote learning can overshadow children\\'s natural curiosity with the pressure to conform and perform. The novella\\'s emphasis on maintaining a sense of wonder serves as a reminder to nurture imagination and remain open to possibilities, fostering innovation and personal growth. The importance of preserving creativity in children is evident in initiatives like STEM education and arts programs, which strive to balance analytical skills with creative thinking.\\n\\nMoreover, \"The Little Prince\" addresses themes of loneliness and isolation, which are increasingly relevant in today\\'s fast-paced world. Despite living in an era of unprecedented connectivity, many individuals experience profound loneliness and disconnection. The Little Prince’s travels and his longing for his rose underscore the universal human desire for companionship and belonging. This theme encourages readers to seek deeper connections with others and to appreciate the beauty of relationships, fostering a sense of community and shared humanity. In modern times, movements promoting mental health awareness and community engagement highlight the need for connection in combating loneliness, with programs such as community meet-ups and online support groups providing avenues for social interaction.\\n\\nWhile technology can contribute to isolation, it also offers opportunities for new forms of connection and creativity. Virtual reality, for instance, allows for immersive experiences that can bring people closer together, transcending geographical barriers. This duality acknowledges the complexity of modern life, where technology can both hinder and enhance human interaction.\\n\\nIn conclusion, \"The Little Prince\" remains a timeless exploration of the human condition, offering valuable insights into relationships, priorities, and the essence of life. Its message of seeing with the heart, critiquing adult preoccupations, and celebrating childlike wonder is deeply relevant in today\\'s world. As we navigate the complexities of modern life, the novella serves as a gentle reminder to cherish genuine connections, reevaluate our priorities, and embrace the wonder of existence. By incorporating its lessons into our lives, we can foster a more compassionate and fulfilling world. Practical applications of these lessons might include engaging in mindfulness practices, prioritizing face-to-face interactions, and encouraging creativity through playful activities. Through its enduring wisdom, \"The Little Prince\" continues to inspire readers to live authentically and to view the world with both curiosity and compassion.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 939, 'prompt_tokens': 3967, 'total_tokens': 4906, 'prompt_tokens_details': {'cached_tokens': 3328, 'audio_tokens': 0}, 'completion_tokens_details': {'reasoning_tokens': 0, 'audio_tokens': 0, 'accepted_prediction_tokens': 0, 'rejected_prediction_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_45cf54deae', 'finish_reason': 'stop', 'logprobs': None}, id='run-9d61d51f-8007-4a6b-b494-d85fcc43d517-0', usage_metadata={'input_tokens': 3967, 'output_tokens': 939, 'total_tokens': 4906})]}}\n",
      "---\n"
     ]
    }
   ],
   "source": [
    "async for event in graph.astream(\n",
    "    {\n",
    "        \"messages\": [\n",
    "            HumanMessage(\n",
    "                content=\"Generate an essay on the topicality of The Little Prince and its message in modern life\"\n",
    "            )\n",
    "        ],\n",
    "    },\n",
    "    config,\n",
    "):\n",
    "    print(event)\n",
    "    print(\"---\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "cb88d5ca-7faf-47f8-b458-d80c0419ea80",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:09:37.871622Z",
     "iopub.status.busy": "2024-11-10T14:09:37.871111Z",
     "iopub.status.idle": "2024-11-10T14:09:51.282395Z",
     "shell.execute_reply": "2024-11-10T14:09:51.280239Z",
     "shell.execute_reply.started": "2024-11-10T14:09:37.871574Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "generation node ['human', 'ai', 'human', 'ai', 'human', 'ai', 'human', 'ai', 'human']\n"
     ]
    }
   ],
   "source": [
    "resp = await graph.ainvoke({\n",
    "        \"messages\": [\n",
    "            HumanMessage(\n",
    "                content=\"Generate an essay on the topicality of The Little Prince and its message in modern life\"\n",
    "            )\n",
    "        ],\n",
    "    },\n",
    "    config,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "58797b70-87da-4d77-8bfa-7131dcc05fea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-10T14:09:51.285091Z",
     "iopub.status.busy": "2024-11-10T14:09:51.284525Z",
     "iopub.status.idle": "2024-11-10T14:09:51.293456Z",
     "shell.execute_reply": "2024-11-10T14:09:51.291662Z",
     "shell.execute_reply.started": "2024-11-10T14:09:51.285043Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "human\n",
      "ai\n",
      "human\n",
      "ai\n",
      "human\n",
      "ai\n",
      "human\n",
      "ai\n",
      "human\n",
      "ai\n"
     ]
    }
   ],
   "source": [
    "for msg in resp['messages']:\n",
    "    print(msg.type)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "340a308e-a546-4e07-93d2-cffbc2654a4c",
   "metadata": {},
   "source": [
    "### External Tools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "391c3939-470f-4b2e-be3e-724cb76fa53e",
   "metadata": {},
   "source": [
    "- https://github.com/langchain-ai/langgraph/blob/main/docs/docs/tutorials/reflexion/reflexion.ipynb\n",
    "- https://arxiv.org/abs/2303.11366\n",
    "    - Reflexion: Language Agents with Verbal Reinforcement Learning\n",
    "- The paper outlines 3 main components:\n",
    "    - Actor (agent) with self-reflection\n",
    "    - External evaluator (task-specific, e.g. code compilation steps)\n",
    "    - Episodic memory that stores the reflections from (1)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9992f501-2018-4b59-b4d8-768e1bc9cb14",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T14:59:42.501591Z",
     "iopub.status.busy": "2024-11-11T14:59:42.501183Z",
     "iopub.status.idle": "2024-11-11T14:59:42.512204Z",
     "shell.execute_reply": "2024-11-11T14:59:42.510290Z",
     "shell.execute_reply.started": "2024-11-11T14:59:42.501555Z"
    }
   },
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "assert load_dotenv()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5bbd5d0b-3f91-4db5-b067-90c9f3b782fc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T14:59:57.235439Z",
     "iopub.status.busy": "2024-11-11T14:59:57.235144Z",
     "iopub.status.idle": "2024-11-11T14:59:57.298712Z",
     "shell.execute_reply": "2024-11-11T14:59:57.296988Z",
     "shell.execute_reply.started": "2024-11-11T14:59:57.235415Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4o-2024-08-06\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d3c942fa-ee4e-44b9-b03b-c3f8a6bcd6d7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:00:14.260020Z",
     "iopub.status.busy": "2024-11-11T15:00:14.259692Z",
     "iopub.status.idle": "2024-11-11T15:00:14.376082Z",
     "shell.execute_reply": "2024-11-11T15:00:14.374523Z",
     "shell.execute_reply.started": "2024-11-11T15:00:14.259996Z"
    }
   },
   "outputs": [],
   "source": [
    "# tools\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper\n",
    "\n",
    "search = TavilySearchAPIWrapper()\n",
    "tavily_tool = TavilySearchResults(api_wrapper=search, max_results=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "1a1b992d-db5a-4e97-aa0f-ad7fc0ddc0ae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:07:11.756306Z",
     "iopub.status.busy": "2024-11-11T15:07:11.755692Z",
     "iopub.status.idle": "2024-11-11T15:07:11.777404Z",
     "shell.execute_reply": "2024-11-11T15:07:11.775440Z",
     "shell.execute_reply.started": "2024-11-11T15:07:11.756256Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain_core.messages import HumanMessage, ToolMessage\n",
    "from langchain_core.output_parsers.openai_tools import PydanticToolsParser\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from pydantic import ValidationError\n",
    "\n",
    "from pydantic import BaseModel, Field\n",
    "\n",
    "\n",
    "class Reflection(BaseModel):\n",
    "    missing: str = Field(description=\"Critique of what is missing.\")\n",
    "    superfluous: str = Field(description=\"Critique of what is superfluous\")\n",
    "\n",
    "# nested\n",
    "class AnswerQuestion(BaseModel):\n",
    "    \"\"\"Answer the question. Provide an answer, reflection, and then follow up with search queries to improve the answer.\"\"\"\n",
    "\n",
    "    answer: str = Field(description=\"~250 word detailed answer to the question.\")\n",
    "    reflection: Reflection = Field(description=\"Your reflection on the initial answer.\")\n",
    "    search_queries: list[str] = Field(\n",
    "        description=\"1-3 search queries for researching improvements to address the critique of your current answer.\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a6ac9ccd-f020-4eac-ace5-c6943a0c384d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:01:47.692113Z",
     "iopub.status.busy": "2024-11-11T15:01:47.691497Z",
     "iopub.status.idle": "2024-11-11T15:01:47.705128Z",
     "shell.execute_reply": "2024-11-11T15:01:47.703288Z",
     "shell.execute_reply.started": "2024-11-11T15:01:47.692062Z"
    }
   },
   "outputs": [],
   "source": [
    "class ResponderWithRetries:\n",
    "    def __init__(self, runnable, validator):\n",
    "        self.runnable = runnable\n",
    "        self.validator = validator\n",
    "\n",
    "    def respond(self, state: dict):\n",
    "        response = []\n",
    "        for attempt in range(3):\n",
    "            response = self.runnable.invoke(\n",
    "                {\"messages\": state[\"messages\"]}, {\"tags\": [f\"attempt:{attempt}\"]}\n",
    "            )\n",
    "            try:\n",
    "                self.validator.invoke(response)\n",
    "                return {\"messages\": response}\n",
    "            except ValidationError as e:\n",
    "                state = state + [\n",
    "                    response,\n",
    "                    ToolMessage(\n",
    "                        content=f\"{repr(e)}\\n\\nPay close attention to the function schema.\\n\\n\"\n",
    "                        + self.validator.schema_json()\n",
    "                        + \" Respond by fixing all validation errors.\",\n",
    "                        tool_call_id=response.tool_calls[0][\"id\"],\n",
    "                    ),\n",
    "                ]\n",
    "        return {\"messages\": response}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3671b4f5-9561-411b-8d1d-8909cff206cc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:01:54.703026Z",
     "iopub.status.busy": "2024-11-11T15:01:54.702448Z",
     "iopub.status.idle": "2024-11-11T15:01:54.713824Z",
     "shell.execute_reply": "2024-11-11T15:01:54.711962Z",
     "shell.execute_reply.started": "2024-11-11T15:01:54.702977Z"
    }
   },
   "outputs": [],
   "source": [
    "import datetime\n",
    "\n",
    "actor_prompt_template = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\n",
    "            \"system\",\n",
    "            \"\"\"You are expert researcher.\n",
    "Current time: {time}\n",
    "\n",
    "1. {first_instruction}\n",
    "2. Reflect and critique your answer. Be severe to maximize improvement.\n",
    "3. Recommend search queries to research information and improve your answer.\"\"\",\n",
    "        ),\n",
    "        MessagesPlaceholder(variable_name=\"messages\"),\n",
    "        (\n",
    "            \"user\",\n",
    "            \"\\n\\n<system>Reflect on the user's original question and the\"\n",
    "            \" actions taken thus far. Respond using the {function_name} function.</reminder>\",\n",
    "        ),\n",
    "    ]\n",
    ").partial(\n",
    "    time=lambda: datetime.datetime.now().isoformat(),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a586cb02-3ccd-457f-9e45-205a67fd822b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:02:02.059443Z",
     "iopub.status.busy": "2024-11-11T15:02:02.059152Z",
     "iopub.status.idle": "2024-11-11T15:02:02.066763Z",
     "shell.execute_reply": "2024-11-11T15:02:02.064640Z",
     "shell.execute_reply.started": "2024-11-11T15:02:02.059419Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m System Message \u001b[0m================================\n",
      "\n",
      "You are expert researcher.\n",
      "Current time: \u001b[33;1m\u001b[1;3m{time}\u001b[0m\n",
      "\n",
      "1. \u001b[33;1m\u001b[1;3m{first_instruction}\u001b[0m\n",
      "2. Reflect and critique your answer. Be severe to maximize improvement.\n",
      "3. Recommend search queries to research information and improve your answer.\n",
      "\n",
      "=============================\u001b[1m Messages Placeholder \u001b[0m=============================\n",
      "\n",
      "\u001b[33;1m\u001b[1;3m{messages}\u001b[0m\n",
      "\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "\n",
      "\n",
      "<system>Reflect on the user's original question and the actions taken thus far. Respond using the \u001b[33;1m\u001b[1;3m{function_name}\u001b[0m function.</reminder>\n"
     ]
    }
   ],
   "source": [
    "actor_prompt_template.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9185926b-65bd-4465-a54d-342e4f37711a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:04:10.060948Z",
     "iopub.status.busy": "2024-11-11T15:04:10.060326Z",
     "iopub.status.idle": "2024-11-11T15:04:10.212577Z",
     "shell.execute_reply": "2024-11-11T15:04:10.210673Z",
     "shell.execute_reply.started": "2024-11-11T15:04:10.060898Z"
    }
   },
   "outputs": [],
   "source": [
    "initial_answer_chain = actor_prompt_template.partial(\n",
    "    first_instruction=\"Provide a detailed ~250 word answer.\",\n",
    "    function_name=AnswerQuestion.__name__,\n",
    ") | llm.bind_tools(tools=[AnswerQuestion])\n",
    "\n",
    "validator = PydanticToolsParser(tools=[AnswerQuestion])\n",
    "\n",
    "first_responder = ResponderWithRetries(\n",
    "    runnable=initial_answer_chain, validator=validator\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "64040fde-dbc7-4467-92e1-00fe71b6150a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:04:27.359283Z",
     "iopub.status.busy": "2024-11-11T15:04:27.358866Z",
     "iopub.status.idle": "2024-11-11T15:04:36.906460Z",
     "shell.execute_reply": "2024-11-11T15:04:36.904492Z",
     "shell.execute_reply.started": "2024-11-11T15:04:27.359249Z"
    }
   },
   "outputs": [],
   "source": [
    "example_question = \"Why is reflection useful in AI?\"\n",
    "initial = first_responder.respond(\n",
    "    {\"messages\": [HumanMessage(content=example_question)]}\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "d021b5ce-a621-4814-9ea1-3c9a57936b69",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-11-11T15:08:00.688580Z",
     "iopub.status.busy": "2024-11-11T15:08:00.687977Z",
     "iopub.status.idle": "2024-11-11T15:08:00.700420Z",
     "shell.execute_reply": "2024-11-11T15:08:00.698340Z",
     "shell.execute_reply.started": "2024-11-11T15:08:00.688528Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'id': 'call_41BHYaAYq2DcRoHtV0NeYr1K',\n",
       " 'function': {'arguments': '{\"answer\":\"Reflection in AI is a pivotal aspect that enhances the robustness, reliability, and adaptability of AI systems. At its core, reflection enables an AI system to analyze its own behavior and decision-making processes. This self-awareness allows AI to identify and correct errors, adapt to new situations, and improve its performance over time. For instance, in natural language processing, reflective AI can evaluate its responses, learn from user interactions, and refine its understanding of language nuances, thereby providing more accurate and contextually appropriate answers.\\\\n\\\\nAdditionally, reflection aids in the transparency and interpretability of AI systems. By having mechanisms to reflect on their operations, AI systems can provide insights into how they reach certain conclusions, which is crucial for debugging and building trust with users. This is particularly important in sensitive applications such as healthcare or autonomous driving, where understanding AI decisions can have significant implications.\\\\n\\\\nMoreover, reflection supports continual learning and adaptation. As AI systems encounter new data, reflective processes help them integrate new information without needing to be retrained from scratch. This capability is essential in dynamic environments where conditions and data inputs constantly change.\\\\n\\\\nOverall, reflection enhances AI systems\\' ability to learn, adapt, and make informed decisions, thereby improving their effectiveness and reliability in real-world applications.\",\"reflection\":{\"missing\":\"The initial answer could delve deeper into specific mechanisms or examples of how reflection is implemented in AI systems. For example, discussing specific algorithms or frameworks that facilitate reflection could provide a more comprehensive understanding.\",\"superfluous\":\"The explanation about reflection helping in transparency and interpretability could be more concise, as it slightly overlaps with explanations on reliability and trust-building, which can be merged for a tighter narrative.\"},\"search_queries\":[\"reflection in AI systems\",\"self-awareness in artificial intelligence\",\"AI transparency and interpretability mechanisms\"]}',\n",
       "  'name': 'AnswerQuestion'},\n",
       " 'type': 'function'}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "initial['messages'].additional_kwargs['tool_calls'][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe812697-d28e-47a8-bac7-acec6ef52880",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "agent",
   "language": "python",
   "name": "agent"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
